package com.nercel.dsj.gksales.api.controller;

import com.nercel.dsj.gksales.service.SmsService;
import com.nercel.dsj.gksales.util.ApiResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author sunlin
 * @date 2019-2-26
 */
@RestController
@Api(tags="短信管理")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SmsApiController {

	private final StringRedisTemplate stringRedisTemplate;
	
	private final SmsService smsService;

	@Value("${app.sms.resendInterval}")
	private Long resendInterval;

	@Value("${app.sms.activeTime}")
	private Long activeTime;

	@ApiOperation(value = "短信发送验证码")
    @RequestMapping(value="/api/v1/sms-vcode", method= RequestMethod.GET)
    public Object sendSmsVCode(
    		@ApiParam(value = "手机号") @RequestParam String phone) {
		String smsPhoneStatusKey = "s_sms_phone_" + phone;
		String cacheStatus = stringRedisTemplate.opsForValue().get(smsPhoneStatusKey);
		if (!StringUtils.isEmpty(cacheStatus)){
			return ApiResultUtil.success(0);
		}

    	String vcode = smsService.sendVerificationCode(phone);
		stringRedisTemplate.opsForValue().set(smsPhoneStatusKey,"1",resendInterval,TimeUnit.SECONDS);

		String smsPhoneValKey = "sms_phone_" + phone;
		stringRedisTemplate.opsForValue().set(smsPhoneValKey,vcode,activeTime,TimeUnit.SECONDS);
		return ApiResultUtil.success(1);
    }

	@ApiOperation(value = "验证短信验证码")
	@RequestMapping(value="/api/v1/sms-vcode/result", method= RequestMethod.GET)
	public Object checkSmsVCode(
			@ApiParam(value = "手机号") @RequestParam String phone,
			@ApiParam(value = "验证码") @RequestParam String vcode) {
		smsService.checkSmsVCode(phone, vcode);
		return ApiResultUtil.success();
	}

	@ApiOperation(value = "短信测试")
	@RequestMapping(value="/api/v1/sms", method= RequestMethod.GET)
	public Object sendAgentRegisteredMessage(
			@ApiParam(value = "手机号") @RequestParam String phone,
			@ApiParam(value = "代理商手机号") @RequestParam String agentPhone
			) {
		smsService.sendAgentRegisteredMessage(phone, agentPhone);
		return ApiResultUtil.success(1);
	}


}
